<template>
  <div class="system-config-list">
    <de-container class="pa-5">
      <div class="header-wrap">
        <el-page-header :content="content" @back="$emit('back')"></el-page-header>
      </div>
      <el-form ref="form" :model="form" :rules="rules" class="demo-ruleForm" label-width="100px">
        <p class="bold">基本信息</p>
        <el-row>
          <el-col :span="12">
            <el-form-item label="消息编码:" prop="configCode">
              <el-input v-model="form.configCode" :disabled="type == 'view'" size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消息名称:" prop="configName">
              <el-input v-model="form.configName" :disabled="type == 'view'" size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消息模板:" prop="templateId">
              <el-select
                v-model="form.templateId"
                :disabled="type == 'view'"
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option v-for="item in templateList" :key="item.id" :label="item.templateName" :value="item.id">
                </el-option>
              </el-select>
              <div class="form-help">
                <p v-show="['notice', 'email', 'feishu_robot'].includes(templateData.sendWay)">
                  消息标题：{{ templateData.title }}
                </p>
                <p v-show="['notice', 'email', 'sms', 'feishu_robot'].includes(templateData.sendWay)">
                  消息内容：{{ templateData.content }}
                </p>
                <p v-show="['notice'].includes(templateData.sendWay)">处理连接：{{ templateData.dealLink || '-' }}</p>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送渠道:" prop="resource">
              <span>{{ sendWayData[templateData.sendWay] }}</span>
              <!--              <el-input size='small'  v-model='form.resource' disabled></el-input>-->
            </el-form-item>
          </el-col>
          <!--          <el-col :span='12'>-->
          <!--            <el-form-item label='发送类型' prop='sendType'>-->
          <!--              <el-radio-group size='small'  v-model='form.sendType'>-->
          <!--                <el-radio label='real'>实时通知</el-radio>-->
          <!--                <el-radio label='timed'>定时通知</el-radio>-->
          <!--              </el-radio-group>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="24"></el-col>
          <template v-if="templateData.sendWay === 'feishu_robot'">
            <el-col :span="12">
              <el-form-item label="飞书ID:" prop="sendParamConfig.feishuAppId">
                <el-input v-model="form.sendParamConfig.feishuAppId" :disabled="type == 'view'" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="飞书密钥:" prop="sendParamConfig.feishuAppSecret">
                <el-input
                  v-model="form.sendParamConfig.feishuAppSecret"
                  :disabled="type == 'view'"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="24" style="float: left">
            <el-form-item label="消息类型:" prop="noticeTypeId">
              <el-cascader
                v-model="form.noticeTypeId"
                :disabled="type == 'view'"
                :options="noticeTree"
                :props="{ checkStrictly: true, label: 'typeName', value: 'id', emitPath: false }"
                clearable
                filterable
                placeholder="请选择"
                size="small"
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消息说明:" prop="not	">
              <el-input
                v-model="form.note"
                :disabled="type == 'view'"
                :row3="4"
                size="small"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" prop="note">
              <el-button v-if="type !== 'view'" size="small" type="primary" @click="handleSendTest">发送测试</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <div>
            <p class="bold">接收角色</p>
            <el-button v-if="type !== 'view'" icon="el-icon-plus" size="mini" type="primary" @click="addRole"
              >添加</el-button
            >
            <div class="selectData">
              <el-tag
                v-for="tag in roleData"
                :key="tag.id"
                :closable="type !== 'view'"
                style="margin-right: 20px; margin-bottom: 10px"
                @close="handleClose(tag, 1)"
              >
                {{ tag.roleName || tag.name }}
              </el-tag>
            </div>
          </div>
          <p class="bold">接收人</p>
          <el-button v-if="type !== 'view'" icon="el-icon-plus" size="mini" type="primary" @click="addUser"
            >添加</el-button
          >
          <div class="selectData">
            <el-tag
              v-for="tag in userData"
              :key="tag.id"
              :closable="type !== 'view'"
              style="margin-right: 20px; margin-bottom: 10px"
              @close="handleClose(tag, 2)"
            >
              {{ tag.userName || tag.name }}
            </el-tag>
          </div>
          <p class="bold">接收部门</p>
          <el-button v-if="type !== 'view'" icon="el-icon-plus" size="mini" type="primary" @click="addDept">
            添加
          </el-button>
          <div class="selectData">
            <el-tag
              v-for="tag in deptData"
              :key="tag.id"
              :closable="type !== 'view'"
              style="margin-right: 20px; margin-bottom: 10px"
              @close="handleClose(tag, 2)"
            >
              {{ tag.deptName || tag.name }}
            </el-tag>
          </div>
        </el-row>
        <el-form-item>
          <el-button v-if="type !== 'view'" size="small" type="primary" @click="handleSubmit('form')">保 存</el-button>
          <el-button icon="el-icon-back" size="small" @click="$emit('back')">{{
            type !== 'view' ? '取消' : '关闭'
          }}</el-button>
        </el-form-item>
      </el-form>
      <testSend
        v-if="sendDialogVisable"
        :dialog-visible="sendDialogVisable"
        :form="form"
        :send-way="templateData.sendWay"
        :template-data="templateData"
        @closeSend="closeSend"
        @confirmSend="confirmSend"
      ></testSend>
      <roleDialog
        v-if="roleDialogVisable"
        :dialog-visible="roleDialogVisable"
        :role-data="roleData"
        @closeRole="closeRole"
      ></roleDialog>
      <userDialog
        v-if="userDialogVisable"
        :dialog-visible="userDialogVisable"
        :user-data="userData"
        @closeUser="closeUser"
      ></userDialog>
      <deptDialog
        v-if="deptDialogVisible"
        :dept-data="deptData"
        :dialog-visible="deptDialogVisible"
        @closeUser="closeDept"
      ></deptDialog>
    </de-container>
  </div>
</template>

<script>
import {
  requesInfoNoticeDetail,
  requestInfoNoticeAdd,
  requestInfoNoticeEdit,
  requestInfoTemplateList,
  requestInfoTypeTree,
} from '@/api'
import roleDialog from '../dialog/roleDialog.vue'
import userDialog from '../dialog/userDialog.vue'
import deptDialog from '../dialog/deptDialog'
import testSend from '../dialog/testSend.vue'
import DeContainer from '@/components/dataease/DeContainer.vue'

export default {
  name: 'Detail',
  components: {
    DeContainer,
    roleDialog,
    userDialog,
    deptDialog,
    testSend,
  },
  props: {
    type: {
      type: String,
      default: '',
    },
    noticeId: {
      type: [String, Number],
      default: '',
    },
  },
  data() {
    return {
      loading: false,
      roleDialogVisable: false,
      sendDialogVisable: false,
      userDialogVisable: false,
      deptDialogVisible: false,
      sendWayData: {
        notice: '站内通知',
        sms: '短信',
        email: '邮箱',
        feishu_robot: '飞书',
      },
      form: {
        configCode: '',
        configName: '',
        note: '',
        noticeTypeId: '',
        noticeTypeName: '',
        personList: [],
        roleList: [],
        sendType: 'real',
        templateId: '',
        sendParamConfig: {
          feishuAppId: '',
          feishuAppSecret: '',
        },
      },
      content: '新增消息通知配置',
      rules: {
        configCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        configName: [{ required: true, message: '请输入', trigger: 'blur' }],
        templateId: [{ required: true, message: '请选择', trigger: 'change' }],
        sendType: [{ required: true, message: '请选择', trigger: 'change' }],
        noticeTypeId: [{ required: true, message: '请选择', trigger: 'change' }],
        'sendParamConfig.feishuAppId': [{ required: true, message: '请输入', trigger: 'blur' }],
        'sendParamConfig.feishuAppSecret': [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      options: [],
      dataArr: [],
      templateList: [],
      noticeTree: [],
      roleData: [],
      userData: [],
      deptData: [],
    }
  },
  computed: {
    templateData() {
      return this.templateList.find((item) => item.id === this.form.templateId) ?? {}
    },
  },
  created() {
    this.content =
      this.type == 'add' ? '新增消息通知配置' : this.type == 'edit' ? '编辑消息通知配置' : '消息通知配置详情'
    this.getTemplateList()
    this.getTreeData()
    this.noticeId && this.getInfo()
  },
  methods: {
    getTemplateList() {
      requestInfoTemplateList({}).then((res) => {
        if (res.success) {
          this.templateList = res.data
        }
      })
    },
    getTreeData() {
      requestInfoTypeTree({
        parentId: 0,
      }).then((res) => {
        if (res.success) {
          this.noticeTree = res.data
        }
      })
    },
    getInfo() {
      requesInfoNoticeDetail({
        id: this.noticeId,
      }).then((res) => {
        if (res.success) {
          this.form = res.data
          this.userData = res.data.personList
          this.roleData = res.data.roleList
          this.deptData = res.data.deptList
        }
      })
    },
    handleClose(tag, type) {
      if (type == 1) {
        this.roleData.splice(this.roleData.indexOf(tag), 1)
        return
      }
      this.userData.splice(this.userData.indexOf(tag), 1)
    },
    addRole() {
      this.roleDialogVisable = true
    },
    addUser() {
      this.userDialogVisable = true
    },
    addDept() {
      this.deptDialogVisible = true
    },
    closeRole(val) {
      this.roleData = this.roleData.concat(val)
      this.roleDialogVisable = false
    },
    closeUser(val) {
      this.userData = this.userData.concat(val)
      this.userDialogVisable = false
    },
    closeDept(val) {
      if (val) {
        this.deptData = val
      }
      this.deptDialogVisible = false
    },
    closeSend(val) {
      this.sendDialogVisable = false
    },
    confirmSend(val) {
      this.sendDialogVisable = false
    },
    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.userData.length && !this.roleData.length && !this.deptData.length) {
            this.$message({
              type: 'error',
              message: '请添加接收人、接收角色或者接收部门',
            })
            return
          }
          let userData = [],
            roleData = [],
            deptData = []
          this.userData.map((item) => {
            userData.push({
              sendType: 'person',
              userName: item.userName || item.name,
              name: item.userName || item.name,
              userId: item.id,
            })
          })
          this.roleData.map((item) => {
            roleData.push({
              sendType: 'role',
              roleName: item.roleName || item.name,
              name: item.roleName || item.name,
              roleId: item.id,
            })
          })
          this.deptData.map((item) => {
            deptData.push({
              sendType: 'dept',
              name: item.deptName,
              deptId: item.deptId,
            })
          })
          this.form.personList = userData
          this.form.roleList = roleData
          this.form.deptList = deptData
          this.form.sendType = 'real'
          this.loading = true
          const api = {
            add: requestInfoNoticeAdd,
            edit: requestInfoNoticeEdit,
          }
          api[this.type](this.form).then((res) => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: res.message,
              })
              this.loading = false
              this.$emit('back')
            } else {
              this.loading = false
              this.$message({
                type: 'error',
                message: res.message,
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSendTest() {
      let pass = true
      this.$refs.form.validateField(
        [
          'noticeTypeId',
          'templateId',
          'configName',
          'configCode',
          'sendParamConfig.feishuAppId',
          'sendParamConfig.feishuAppSecret',
        ],
        (valid) => {
          pass = pass && !valid
        }
      )
      if (pass) {
        this.sendDialogVisable = true
      }
    },
  },
}
</script>

<style lang="scss">
.header-wrap {
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.15);
  margin-bottom: 16px;
}

.bold {
  font-weight: bolder;
  margin: 20px 0;
}
.inline {
  display: flex;
}
.selectData {
  margin: 20px;
  .item {
    height: 20px;
    padding: 5px 10px;
    display: flex;
    align-items: center;
    display: inline-block;
  }
}
.form-help {
  font-size: 12px;
  color: #999999;
}
</style>
